import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    meta: {
      title: "首页"
    },
    component: () => import('../views/Home')
  },
  {
    path: '/login',
    name: 'Login',
    meta: {
      title: '登录'
    },
    component: () => import('../views/login/Login')
  },
  {
    path: '/register',
    name: 'Register',
    meta: {
      title: '注册'
    },
    component: () => import('../views/login/Register')
  },
  {
    path: '/resetPassword',
    name: 'ResetPassword',
    meta: {
      title: '重置密码'
    },
    component: () => import('../views/login/ResetPassword')
  },
  {
    path: '/editPassword',
    name: 'EditPassword',
    meta: {
      title: '修改密码',
      requireAuth: true
    },
    component: () => import('../views/login/EditPassword')
  },
  {
    path: '/user/index',
    name: 'UserIndex',
    meta: {
      title: "个人中心",
      requireAuth: true
    },
    component: () => import('@/views/user/Index')
  },
  {
    path: '/common/agreement',
    name: 'Agreement',
    meta: {
      title: "服务协议"
    },
    component: () => import('@/views/common/Agreement')
  },
  {
    path: '/common/about',
    name: 'About',
    meta: {
      title: "关于我们"
    },
    component: () => import('@/views/common/About')
  },
  {
    path: '/user/UserInfo',
    name: 'UserInfo',
    meta: {
      title: "个人资料",
      requireAuth: true
    },
    component: () => import('@/views/user/UserInfo')
  },
  {
    path: '/user/CertAuth',
    name: 'CertAuth',
    meta: {
      title: "个人认证",
      requireAuth: true
    },
    component: () => import('@/views/user/CertAuth')
  },
  {
    path: '/firstaid/index',
    name: 'firstaid',
    meta: {
      title: "急救知识"
    },
    component: () => import('@/views/firstaid/index')
  },
  {
    path: '/firstAidDetail',
    name: 'firstAidDetail',
    meta: {
      title: "急救详情"
    },
    component: () => import('@/views/firstaid/detail')
  },
]

const router = new VueRouter({
  routes
})

/**
 * 全局前置路由守卫
 */
router.beforeEach(async (to, from, next) => {

  let userInfo = JSON.parse(localStorage.getItem('userInfo'));

  if (to.meta.requireAuth) {
    if (userInfo) {
      if (store.getters.userInfo) {
        next();
      } else {
        store.commit('setUserInfo', userInfo);
        next();
      }
    } else {
      next('/login');
    }
  } else {
    if (userInfo && store.getters.userInfo && to.path === '/login') {
      next('/');
    } else {
      next();
    }
  }
});

export default router
